const { Sequelize, Model } = require('sequelize')
const util = require('util')
const { yushu } = require('../../config/config')
const { sequelize } = require('../../core/db')
const axios = require('axios')
const { Favor } = require('./favor')

// index 值最大为最新一期
//业务表 中间表 index:期刊序号 id:关联实体表期刊信息  type:期刊类型
class Book extends Model {
    // constructor(id) {
    //     super()
    //     this.id = id;
    // }
    // 详情
    async detail(id) {
        const url = util.format(yushu.detailUrl, id)
        const detail = await axios.get(url)
        return detail.data;

    }

    // 搜索 summary 是否是简要信息
    static async searchFromYuShu(q, start, count, summary = 1) {
        const url = util.format(yushu.keywordUrl, encodeURI(q), count, start, summary)
        const result = await axios.get(url)
        return result.data
    }

    // 我喜欢 数量
    static async getMyFavorBookCount(uid){
        const count = await Favor.count({
            where:{
                type:400,
                uid
            }
        })
        return count
    }
    //一本书籍的点赞数量
    static async getBookFavor(uid,bookID){
        //这本图书的点赞数量
        const favorNums = await Favor.count({
            where:{
                art_id:bookID,
                type:400
            }
        })
        // 相对于用户 是否点赞
        const myFavor = await Favor.findOne({
            where:{
                art_id:bookID,
                uid,
                type:400
            }
        })
        return {
            fav_nums:favorNums,
            like_status:myFavor?1:0
        }
    }
}

Book.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true
    },
    fav_nums: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    }
}, {
    sequelize,
    tableName: 'book'
})
module.exports = {
    Book
}